﻿using System;

namespace Rules
{
    public class RangeRule<T> : RuleBase<T> where T : IComparable
    {
        public RangeRule(T minimum, T maximum, string propertyName)
            : this(minimum, maximum, propertyName, null) { }

        public RangeRule(T minimum, T maximum, string propertyName, string description)
            : base(propertyName, description)
        {
            ValidateRange(minimum, maximum);
            Minimum = minimum;
            Maximum = maximum;
        }

        private void ValidateRange(T minimum, T maximum)
        {
            ValidateNotNull(minimum, "minimum");
            ValidateNotNull(maximum, "maximum");
            if (minimum.CompareTo(maximum) >= 0)
            {
                throw new ApplicationException("Minimum must be less than Maximum");
            }
        }

        public T Minimum { get; private set; }
        public T Maximum { get; private set; }

        protected override bool DoEvaluate(T subject)
        {
            return subject.CompareTo(Minimum) >= 0 && subject.CompareTo(Maximum) <= 0;
        }

        protected override string GetDefaultDescription()
        {
            return string.Format("{0} must be between {1} and {2}", PropertyName, Minimum, Maximum);
        }
    }
}
